<template>
  <div class="chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <button @click="goBack" class="back-btn">← 返回</button>
      <div class="role-info">
        <img 
          v-if="currentRole?.avatar" 
          :src="getAvatarUrl(currentRole.avatar)" 
          :alt="currentRole.name"
          class="header-avatar"
          @error="handleImageError"
        />
        <div class="header-text">
          <h2>{{ currentRole?.name || 'AI角色' }}</h2>
          <span class="role-category">{{ currentRole?.category || '通用' }}</span>
        </div>
      </div>
      <div class="chat-info">
        <span>聊天ID: {{ chatStore.currentChatId }}</span>
        <!-- 技能信息区域 -->
        <div class="skill-info" v-if="currentRole?.skillName">
          <div class="skill-header">
            <span class="skill-name">
              <span class="skill-icon">✨</span>
              {{ currentRole.skillName }}
            </span>
          </div>
          <div class="skill-description">
            {{ currentRole.skillDescription }}
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div
        v-for="message in chatStore.chatHistory"
        :key="message.id"
        :class="['message', message.type]"
      >
        <div class="message-avatar">
          <img 
            v-if="message.type === 'ai' && currentRole?.avatar" 
            :src="getAvatarUrl(currentRole.avatar)" 
            :alt="currentRole.name"
            @error="handleImageError"
            class="avatar-image"
          />
          <span v-else-if="message.type === 'user'">我</span>
          <span v-else>AI</span>
        </div>
        <div class="message-content" :class="{ completed: !message.isLoading }">
          <div v-if="message.isLoading && !message.content" class="loading">
            <span>AI正在思考中...</span>
          </div>
          <div v-else-if="message.content">{{ message.content }}</div>
        </div>
      </div>
      
      <!-- 错误提示 -->
      <div v-if="chatStore.error" class="error-message">
        {{ chatStore.error }}
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <div class="input-container">
        <input
          v-model="inputMessage"
          type="text"
          class="input"
          placeholder="输入消息..."
          @keyup.enter="sendMessage"
          :disabled="chatStore.isLoading"
        />
        <!-- 技能按钮 -->
        <button
          v-if="currentRole?.skillName"
          @click="toggleSkill"
          class="btn btn-skill"
          :class="{ active: useSkill }"
          :disabled="chatStore.isLoading"
          :title="getSkillTooltip()"
        >
          <span class="skill-icon">✨</span>
          <span v-if="useSkill" class="skill-text">已激活</span>
        </button>
        <!-- 语音输入按钮 -->
        <button
          @click="toggleVoiceInput"
          class="btn btn-voice"
          :class="{ active: isRecording, disabled: !isVoiceSupported }"
          :disabled="chatStore.isLoading || !isVoiceSupported"
          :title="isVoiceSupported ? (isRecording ? '点击停止录音' : '点击开始录音') : '浏览器不支持语音识别'"
        >
          <span v-if="isRecording" class="voice-icon recording">🎤</span>
          <span v-else class="voice-icon">🎙️</span>
        </button>
        <button
          @click="sendMessage"
          class="btn btn-primary"
          :disabled="!inputMessage.trim() || chatStore.isLoading"
        >
          发送
        </button>
      </div>
      <!-- 语音识别状态提示 -->
      <div v-if="voiceStatus" class="voice-status" :class="voiceStatusClass">
        <span>{{ voiceStatus }}</span>
        <button 
          v-if="isPlaying" 
          @click="stopVoicePlayback" 
          class="stop-voice-btn"
          title="点击停止语音播放"
        >
          ⏹️
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useChatStore } from '../stores/chatStore'
import { useRoleStore } from '../stores/roleStore'
import { chatAPI } from '../api'

export default {
  name: 'Chat',
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const router = useRouter()
    const route = useRoute()
    const chatStore = useChatStore()
    const roleStore = useRoleStore()
    const inputMessage = ref('')
    const messagesContainer = ref(null)
    let eventSource = null

    // 当前角色
    const currentRole = ref(null)
    
    // 技能状态
    const useSkill = ref(false)

    // 语音识别相关状态
    const isRecording = ref(false)
    const isVoiceSupported = ref(false)
    const voiceStatus = ref('')
    const voiceStatusClass = ref('')
    
    // 语音合成相关状态
    const currentAudio = ref(null)
    const isPlaying = ref(false)
    let recognition = null

    // 页面加载时初始化
    onMounted(async () => {
      await initializeChat()
      initializeVoiceRecognition()
    })

    // 页面卸载时清理资源
    onUnmounted(() => {
      if (eventSource) {
        eventSource.close()
      }
      if (recognition) {
        recognition.stop()
      }
      // 停止语音播放
      stopVoicePlayback()
    })

    // 监听消息变化，自动滚动到底部
    watch(
      () => chatStore.chatHistory.length,
      () => {
        nextTick(() => {
          scrollToBottom()
        })
      }
    )

    // 初始化聊天
    const initializeChat = async () => {
      try {
        // 获取角色信息
        await roleStore.fetchRoles()
        currentRole.value = roleStore.roles.find(role => role.id === props.roleId)
        
        if (!currentRole.value) {
          chatStore.setError('角色不存在')
          return
        }

        // 设置当前角色
        chatStore.setCurrentRole(currentRole.value)
      } catch (error) {
        console.error('初始化聊天失败:', error)
        chatStore.setError('初始化聊天失败')
      }
    }

    // 初始化语音识别
    const initializeVoiceRecognition = () => {
      // 检查浏览器是否支持语音识别
      const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
      
      if (!SpeechRecognition) {
        console.log('浏览器不支持语音识别')
        isVoiceSupported.value = false
        return
      }

      isVoiceSupported.value = true
      recognition = new SpeechRecognition()
      
      // 配置语音识别参数
      recognition.continuous = false // 改为非连续识别，避免自动重启
      recognition.interimResults = true // 显示中间结果
      recognition.lang = 'zh-CN' // 设置语言为中文
      recognition.maxAlternatives = 1 // 最多返回1个结果

      // 语音识别开始
      recognition.onstart = () => {
        // 注意：这里不设置isRecording.value，由startVoiceInput函数统一管理
        voiceStatus.value = '正在听取您的语音...'
        voiceStatusClass.value = 'listening'
        console.log('语音识别开始')
      }

      // 语音识别结果
      recognition.onresult = (event) => {
        let finalTranscript = ''
        let interimTranscript = ''

        for (let i = event.resultIndex; i < event.results.length; i++) {
          const transcript = event.results[i][0].transcript
          if (event.results[i].isFinal) {
            finalTranscript += transcript
          } else {
            interimTranscript += transcript
          }
        }

        // 累积最终结果到输入框
        if (finalTranscript) {
          inputMessage.value += finalTranscript
          voiceStatus.value = `已识别: ${inputMessage.value}`
          voiceStatusClass.value = 'success'
        }

        // 显示当前识别中的文本
        if (interimTranscript) {
          voiceStatus.value = `识别中: ${inputMessage.value}${interimTranscript}`
          voiceStatusClass.value = 'interim'
        } else if (finalTranscript) {
          voiceStatus.value = `已识别: ${inputMessage.value}`
          voiceStatusClass.value = 'success'
        }
      }

      // 语音识别错误
      recognition.onerror = (event) => {
        console.error('语音识别错误:', event.error)
        isRecording.value = false
        
        let errorMessage = '语音识别失败'
        switch (event.error) {
          case 'no-speech':
            errorMessage = '未检测到语音，请重试'
            break
          case 'audio-capture':
            errorMessage = '无法访问麦克风，请检查权限'
            break
          case 'not-allowed':
            errorMessage = '麦克风权限被拒绝'
            break
          case 'network':
            errorMessage = '网络错误，请检查网络连接'
            break
          default:
            errorMessage = `语音识别错误: ${event.error}`
        }
        
        voiceStatus.value = errorMessage
        voiceStatusClass.value = 'error'
        
        // 3秒后清除错误状态
        setTimeout(clearVoiceStatus, 3000)
      }

      // 语音识别结束
      recognition.onend = () => {
        console.log('语音识别结束，当前录音状态:', isRecording.value)
        
        // 由于改为非连续模式，识别结束后不会自动重启
        // 只需要确保状态正确更新
        if (isRecording.value) {
          console.log('识别意外结束，更新状态')
          isRecording.value = false
          voiceStatus.value = '识别结束'
          voiceStatusClass.value = 'success'
          setTimeout(clearVoiceStatus, 2000)
        } else {
          console.log('正常结束或用户主动停止')
        }
      }
    }

    // 切换技能
    const toggleSkill = () => {
      if (chatStore.isLoading) {
        return
      }
      useSkill.value = !useSkill.value
      
      if (useSkill.value) {
        console.log(`已激活 ${currentRole.value?.skillName} 技能`)
      } else {
        console.log(`已关闭 ${currentRole.value?.skillName} 技能`)
      }
    }

    // 获取技能提示信息
    const getSkillTooltip = () => {
      if (!currentRole.value?.skillName) {
        return ''
      }
      
      const status = useSkill.value ? '已激活' : '未激活'
      const action = useSkill.value ? '点击关闭' : '点击激活'
      
      return `${currentRole.value.skillName} (${status})\n${currentRole.value.skillDescription}\n\n${action}技能`
    }

    // 切换语音输入
    const toggleVoiceInput = () => {
      if (!isVoiceSupported.value || chatStore.isLoading) {
        return
      }

      if (isRecording.value) {
        stopVoiceInput()
      } else {
        startVoiceInput()
      }
    }


    // 开始语音输入
    const startVoiceInput = () => {
      console.log('尝试开始语音输入，当前状态:', isRecording.value)
      
      if (!recognition) {
        voiceStatus.value = '语音识别未初始化'
        voiceStatusClass.value = 'error'
        return
      }

      if (isRecording.value) {
        console.log('语音识别已在运行中，跳过启动')
        return
      }

      try {
        // 开始录音时清空输入框
        inputMessage.value = ''
        clearVoiceStatus()
        
        // 设置录音状态
        isRecording.value = true
        console.log('已设置录音状态为true')
        
        recognition.start()
        console.log('已调用recognition.start()')
      } catch (error) {
        console.error('启动语音识别失败:', error)
        voiceStatus.value = '启动语音识别失败'
        voiceStatusClass.value = 'error'
        isRecording.value = false
        setTimeout(clearVoiceStatus, 3000)
      }
    }

    // 停止语音输入
    const stopVoiceInput = () => {
      console.log('尝试停止语音输入，当前状态:', isRecording.value)
      
      if (recognition && isRecording.value) {
        // 先更新状态，防止自动重启
        isRecording.value = false
        console.log('已设置录音状态为false')
        
        try {
          recognition.stop()
          console.log('已调用recognition.stop()')
        } catch (error) {
          console.error('停止语音识别失败:', error)
        }
        
        // 停止录音后显示最终结果
        if (inputMessage.value.trim()) {
          voiceStatus.value = `录音完成: ${inputMessage.value}`
          voiceStatusClass.value = 'success'
        } else {
          voiceStatus.value = '录音结束，未识别到语音'
          voiceStatusClass.value = 'error'
        }
        
        // 3秒后清除状态
        setTimeout(clearVoiceStatus, 3000)
      } else {
        console.log('语音识别未运行或状态不正确')
      }
    }

    // 清除语音状态
    const clearVoiceStatus = () => {
      voiceStatus.value = ''
      voiceStatusClass.value = ''
    }

    // 停止语音播放
    const stopVoicePlayback = () => {
      if (currentAudio.value) {
        currentAudio.value.pause()
        currentAudio.value.currentTime = 0
        currentAudio.value = null
      }
      isPlaying.value = false
      voiceStatus.value = '语音播放已停止'
      voiceStatusClass.value = 'success'
      
      // 3秒后清除状态
      setTimeout(() => {
        if (voiceStatus.value === '语音播放已停止') {
          voiceStatus.value = ''
          voiceStatusClass.value = ''
        }
      }, 3000)
    }

    // 发送消息
    const sendMessage = async () => {
      const message = inputMessage.value.trim()
      if (!message || chatStore.isLoading) return

      try {
        // 清空输入框
        inputMessage.value = ''
        
        // 开始聊天
        const aiMessage = chatStore.startChat(message)
        
        // 创建SSE连接
        eventSource = chatAPI.createSSEConnection(
          props.roleId,
          message,
          chatStore.currentChatId,
          null, // voice参数
          useSkill.value // 技能参数
        )

        // 设置连接超时
        let connectTimeout = setTimeout(() => {
          if (eventSource && eventSource.readyState === EventSource.CONNECTING) {
            console.log('SSE连接超时')
            chatStore.setError('连接超时，请重试')
            chatStore.finishAIMessage(aiMessage.id)
            eventSource.close()
            eventSource = null
          }
        }, 10000) // 10秒超时

        // 监听SSE连接打开
        eventSource.onopen = () => {
          console.log('SSE连接已建立')
          // 清除超时定时器
          if (connectTimeout) {
            clearTimeout(connectTimeout)
          }
        }

        // 监听SSE消息
        let messageReceived = false
        eventSource.onmessage = (event) => {
          if (event.data) {
            chatStore.updateAIMessage(aiMessage.id, event.data)
            messageReceived = true
          }
        }

        // 监听语音合成事件
        eventSource.addEventListener('voice-start', (event) => {
          console.log('语音合成开始:', event.data)
          voiceStatus.value = '开始语音合成...'
          voiceStatusClass.value = 'listening'
        })

        eventSource.addEventListener('voice-data', (event) => {
          console.log('收到音频数据，Base64长度:', event.data.length)
          try {
            // 将Base64字符串转换为二进制数据
            const binaryString = atob(event.data)
            const bytes = new Uint8Array(binaryString.length)
            for (let i = 0; i < binaryString.length; i++) {
              bytes[i] = binaryString.charCodeAt(i)
            }
            
            // 创建Blob对象
            const audioBlob = new Blob([bytes], { type: 'audio/mpeg' })
            console.log('创建音频Blob，大小:', audioBlob.size, 'bytes')
            
            const audioUrl = URL.createObjectURL(audioBlob)
            console.log('创建音频URL:', audioUrl)
            
            // 创建音频对象并播放
            const audio = new Audio(audioUrl)
            currentAudio.value = audio
            
            audio.onloadeddata = () => {
              console.log('音频数据加载完成，时长:', audio.duration, '秒')
            }
            
            audio.oncanplay = () => {
              console.log('音频可以播放了')
            }
            
            audio.onended = () => {
              console.log('音频播放结束')
              URL.revokeObjectURL(audioUrl)
              currentAudio.value = null
              isPlaying.value = false
            }
            
            audio.onerror = (error) => {
              console.error('音频播放错误:', error)
              voiceStatus.value = '音频播放失败'
              voiceStatusClass.value = 'error'
            }
            
            // 播放音频
            audio.play().then(() => {
              console.log('音频开始播放')
              isPlaying.value = true
              voiceStatus.value = '正在播放语音...'
              voiceStatusClass.value = 'success'
            }).catch(error => {
              console.error('音频播放失败:', error)
              isPlaying.value = false
              voiceStatus.value = '音频播放失败: ' + error.message
              voiceStatusClass.value = 'error'
            })
            
          } catch (error) {
            console.error('处理音频数据失败:', error)
            voiceStatus.value = '音频数据处理失败: ' + error.message
            voiceStatusClass.value = 'error'
          }
        })

        eventSource.addEventListener('voice-complete', (event) => {
          console.log('语音合成完成:', event.data)
          voiceStatus.value = '语音播放完成'
          voiceStatusClass.value = 'success'
          
          // 3秒后清除状态
          setTimeout(() => {
            if (voiceStatus.value === '语音播放完成') {
              voiceStatus.value = ''
              voiceStatusClass.value = ''
            }
          }, 3000)
        })

        eventSource.addEventListener('voice-error', (event) => {
          console.error('语音合成错误:', event.data)
          voiceStatus.value = event.data || '语音合成失败'
          voiceStatusClass.value = 'error'
        })

        // 监听SSE错误
        let errorCount = 0
        eventSource.onerror = (error) => {
          errorCount++
          
          // 如果已经收到消息，这个错误是正常的连接结束
          if (messageReceived) {
            console.log(`SSE连接结束 (${errorCount}): 对话完成`)
            console.log('EventSource状态:', eventSource.readyState)
            console.log('连接URL:', eventSource.url)
          } else {
            console.error(`SSE连接错误 (${errorCount}):`, error)
            console.error('EventSource状态:', eventSource.readyState)
            console.error('连接URL:', eventSource.url)
          }
          
          // 防止无限重连
          if (errorCount > 5) {
            console.error('错误次数过多，停止重连')
            chatStore.setError('连接失败，请刷新页面重试')
            chatStore.finishAIMessage(aiMessage.id)
            if (eventSource) {
              eventSource.close()
              eventSource = null
            }
            return
          }
          
          // EventSource状态: 0=CONNECTING, 1=OPEN, 2=CLOSED
          if (eventSource.readyState === EventSource.CONNECTING) {
            // 如果已经收到消息，说明对话完成，这是正常的连接结束
            if (messageReceived) {
              console.log('✅ 对话完成，连接正常结束')
              chatStore.finishAIMessage(aiMessage.id)
              if (eventSource) {
                eventSource.close()
                eventSource = null
              }
              return
            }
            console.log('连接中，继续等待...')
            // 不立即关闭，给连接一些时间
            return
          } else if (eventSource.readyState === EventSource.CLOSED) {
            console.log('连接已关闭')
            chatStore.finishAIMessage(aiMessage.id)
            if (eventSource) {
              eventSource.close()
              eventSource = null
            }
          } else {
            // 如果没有收到消息就出错，才是真正的错误
            if (!messageReceived) {
              console.log('连接失败，等待重连...')
            } else {
              console.log('✅ 连接正常结束')
            }
          }
        }

        // 监听SSE关闭
        eventSource.onclose = () => {
          chatStore.finishAIMessage(aiMessage.id)
          if (eventSource) {
            eventSource.close()
            eventSource = null
          }
        }

      } catch (error) {
        console.error('发送消息失败:', error)
        chatStore.setError('发送消息失败')
      }
    }

    // 返回主页
    const goBack = () => {
      if (eventSource) {
        eventSource.close()
      }
      // 停止语音播放
      stopVoicePlayback()
      router.push('/')
    }

    // 获取头像URL
    const getAvatarUrl = (avatar) => {
      if (!avatar) {
        return '/default-avatar.svg' // 默认头像
      }
      
      // 如果是完整的URL，直接返回
      if (avatar.startsWith('http')) {
        return avatar
      }
      
      // 如果是相对路径，通过代理路径访问头像文件
      return `/api/${avatar}`
    }

    // 处理头像加载错误
    const handleImageError = (event) => {
      event.target.src = '/default-avatar.svg'
    }

    // 滚动到底部
    const scrollToBottom = () => {
      if (messagesContainer.value) {
        messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
      }
    }

    return {
      chatStore,
      currentRole,
      inputMessage,
      messagesContainer,
      sendMessage,
      goBack,
      getAvatarUrl,
      handleImageError,
      // 技能相关
      useSkill,
      toggleSkill,
      getSkillTooltip,
      // 语音识别相关
      isRecording,
      isVoiceSupported,
      voiceStatus,
      voiceStatusClass,
      toggleVoiceInput,
      // 语音播放相关
      isPlaying,
      stopVoicePlayback,
    }
  }
}
</script>

<style scoped>
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.role-info {
  display: flex;
  align-items: center;
  gap: 16px;
  flex: 1;
  justify-content: center;
}

.header-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid rgba(255, 255, 255, 0.3);
  box-shadow: var(--shadow-soft);
  transition: all 0.3s ease;
}

/* 消息头像中的图片 */
.message-avatar .avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: none;
}

.role-info:hover .header-avatar {
  transform: scale(1.1);
  border-color: var(--accent-blue);
  box-shadow: 0 8px 25px rgba(0, 212, 255, 0.3);
}

.header-text h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  background: var(--gradient-accent);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.header-text .role-category {
  font-size: 12px;
  color: var(--text-secondary);
  margin-left: 8px;
  padding: 4px 8px;
  background: var(--surface-glass);
  border-radius: 12px;
  backdrop-filter: blur(10px);
}

.chat-info {
  font-size: 11px;
  color: var(--text-muted);
  background: var(--surface-glass);
  padding: 6px 12px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 技能信息区域样式 */
.skill-info {
  background: rgba(255, 215, 0, 0.1);
  border: 1px solid rgba(255, 215, 0, 0.3);
  border-radius: 8px;
  padding: 8px 12px;
  margin-top: 8px;
}

.skill-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.skill-name {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  font-weight: 600;
  color: var(--text-primary);
}

.skill-name .skill-icon {
  font-size: 14px;
  animation: sparkle 2s infinite;
}


.skill-description {
  font-size: 10px;
  color: var(--text-secondary);
  line-height: 1.4;
  margin-top: 4px;
}

/* 技能按钮样式 */
.btn-skill {
  background: linear-gradient(135deg, #ffd700 0%, #ffb347 100%);
  border: none;
  color: white;
  min-width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(255, 215, 0, 0.3);
}

.btn-skill:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 215, 0, 0.4);
}

.btn-skill.active {
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  box-shadow: 0 4px 15px rgba(40, 167, 69, 0.4);
  animation: pulse 1.5s infinite;
}

.btn-skill.disabled {
  background: #ccc;
  cursor: not-allowed;
  box-shadow: none;
}

.skill-icon {
  font-size: 18px;
  transition: all 0.3s ease;
}

.skill-text {
  font-size: 11px;
  margin-left: 4px;
  font-weight: 500;
}

.btn-skill.active .skill-icon {
  animation: sparkle 1s infinite;
}


/* 技能图标动画 */
@keyframes sparkle {
  0%, 100% {
    transform: scale(1) rotate(0deg);
    opacity: 1;
  }
  50% {
    transform: scale(1.2) rotate(180deg);
    opacity: 0.8;
  }
}

.error-message {
  background: rgba(255, 107, 107, 0.1);
  color: var(--accent-red);
  padding: 12px 16px;
  border-radius: 12px;
  margin: 16px 0;
  border: 1px solid rgba(255, 107, 107, 0.3);
  backdrop-filter: blur(10px);
}

.input-container {
  display: flex;
  gap: 10px;
}

.input-container input {
  flex: 1;
}

.input-container button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 语音按钮样式 */
.btn-voice {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  min-width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.btn-voice:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.btn-voice.active {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  box-shadow: 0 4px 15px rgba(255, 107, 107, 0.4);
  animation: pulse 1.5s infinite;
}

.btn-voice.disabled {
  background: #ccc;
  cursor: not-allowed;
  box-shadow: none;
}

.voice-icon {
  font-size: 18px;
  transition: all 0.3s ease;
}

.voice-icon.recording {
  animation: recording 0.8s infinite alternate;
}

/* 语音状态提示样式 */
.voice-status {
  margin-top: 8px;
  padding: 8px 12px;
  border-radius: 8px;
  font-size: 13px;
  text-align: center;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.voice-status.listening {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
  border: 1px solid rgba(102, 126, 234, 0.3);
}

.voice-status.interim {
  background: rgba(255, 193, 7, 0.1);
  color: #ffc107;
  border: 1px solid rgba(255, 193, 7, 0.3);
}

.voice-status.success {
  background: rgba(40, 167, 69, 0.1);
  color: #28a745;
  border: 1px solid rgba(40, 167, 69, 0.3);
}

.voice-status.error {
  background: rgba(220, 53, 69, 0.1);
  color: #dc3545;
  border: 1px solid rgba(220, 53, 69, 0.3);
}

/* 停止语音按钮样式 */
.stop-voice-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 6px;
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
}

.stop-voice-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}


/* 动画效果 */
@keyframes pulse {
  0% {
    box-shadow: 0 4px 15px rgba(255, 107, 107, 0.4);
  }
  50% {
    box-shadow: 0 6px 25px rgba(255, 107, 107, 0.6);
  }
  100% {
    box-shadow: 0 4px 15px rgba(255, 107, 107, 0.4);
  }
}

@keyframes recording {
  0% {
    transform: scale(1);
  }
  100% {
    transform: scale(1.1);
  }
}

.loading {
  display: flex;
  align-items: center;
  gap: 10px;
  color: #666;
  font-style: italic;
}

.loading::after {
  content: '';
  width: 12px;
  height: 12px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #007bff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
